package com.hyt.it.ogt.kq.common.bm.config;

import com.hyt.it.ogt.kq.common.config.ConfigManager;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * RabbitMQ配置
 *
 * @author huangwu
 * @date 2022-09-05
 */
@Configuration
public class RabbitMqConfig {

    @Resource
    private RabbitAdmin rabbitAdmin;

    @Resource
    private ConfigManager configManager;

    /**
     * 消息实际消费队列所绑定的交换机
     */
    @Bean
    DirectExchange direct() {
        return (DirectExchange) ExchangeBuilder.directExchange(configManager.getDirect()).durable(true).build();
    }


    /**
     * 集体报名考生信息更新消费队列
     */
    @Bean
    public Queue pushGroupRegistrationQueue() {
        return new Queue(configManager.getGroupRegistrationQueue());
    }

    /**
     * 将集体报名考生信息更新队列绑定到交换机
     */
    @Bean
    Binding pushPjDataBinding() {
        return BindingBuilder.bind(pushGroupRegistrationQueue()).to(direct()).with(configManager.getGroupRegistrationRoute());
    }


    /**
     * 创建初始化RabbitAdmin对象
     * AutoStartup只有设置为 true，spring 才会加载 RabbitAdmin 这个类
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    /**
     * 创建交换机和对列
     */
    @Bean
    void createExchangeQueue() {
        rabbitAdmin.declareExchange(direct());
        rabbitAdmin.declareQueue(pushGroupRegistrationQueue());
    }

}
